package com.tang.managementdemo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Data
@Component
public class JwtUtils {

    @Value("${jwt.signKey}")
    private String signKey;
    @Value("${jwt.expire}")
    private Long expire;

    Map<String, Object> header = new HashMap<>();
    public JwtUtils(){
        header.put("typ","JWT");
        header.put("alg","HS256");
    }
    /**
     * 生成JWT令牌
     * @return
     */
    public String generateJwt(Map<String,Object> claims){
//        System.out.println(claims.get("id")+"====");
        String jwt = Jwts.builder()
                .setHeader(header)
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, signKey)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .compact();
        return jwt;
    }

    /**
     * 解析JWT令牌
     * @param jwt JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public Claims parseJWT(String jwt){
        Claims claims = Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
//        System.out.println(claims.get("id")+"++++++++=");
//        System.out.println(claims.get("username"));
//        System.out.println(claims.get("name"));
//        System.out.println(claims.get("phone"));
        return claims;
    }
    public JwsHeader getHeader(String jwt){
        JwsHeader jwsHeader = Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getHeader();
        return jwsHeader;
    }
}
